package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Course;
import model.Session;

import database.DBHandler;

/**
 * Servlet implementation class Search
 */
public class Search extends AServlet implements Servlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		if (session == null || session.getAttribute("LoginStatus") == null
				|| !(Boolean) session.getAttribute("LoginStatus")) {
			response.sendRedirect("index.jsp");
			return;
		}
		
		if (request.getParameter("searchName") != null && request.getParameter("searchDesc") != null) {
			String searchName = new String(request.getParameter("searchName"));
			String searchDesc = new String(request.getParameter("searchDesc"));
			PrintWriter out = response.getWriter();
			Connection con = DBHandler.getHandler().getLocalCon();
			try {
				ArrayList<Course> res = DBHandler.getHandler().makeSearch(searchName, searchDesc, con);
				out.println("<h2>Showing results:</h2>");
				for (Course c : res){
					out.println("<h3 class=\"inline\">" + c.getCourseName() + "</h3><br />");
					out.println(c.getDescription() + "<br />");
					out.println("Group: " + c.getGroupNum() + ", ");
					out.println("Points: " + c.numOfpts() + ", ");
					out.println("Capacity: " + c.getCapacity() + ", ");
					out.println("Registered: " + c.getNumOfRegistered() + "<br />");
					out.println("<h4>Session held on: </h4>");
					ArrayList<Session> sessions = c.getSessions();
					for (Session s : sessions){
						out.println("<b>" + s.getNamedDay() + "</b>: starts on hour " + s.getStart() + 
								" goes for " + (s.getEnd() - s.getStart()));
					}
					out.println("<hr />");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			finishTransaction(con, true);
			DBHandler.getHandler().returnLocalCon(con);
			return;
		}

		RequestDispatcher rd = getServletConfig().getServletContext()
				.getRequestDispatcher("/WEB-INF/JSP-Files/search.jsp");
		rd.forward(request, response);
		return;
	}
}
